

import 'dart:async';

import 'package:cave_flutter/common/chat_manager.dart';
import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/utils/extension/string_extension.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nertc_core/nertc_core.dart';

import '../../../common/chat_rtc_manager.dart';
import '../../../routes/whl_app_pages.dart';
import '../../../utils/event_bus_utils.dart';
import '../../whl_main/whl_main_logic.dart';

class SmallCallWidget extends StatefulWidget {

  // bool? isVideoCall;
  SmallCallWidget({super.key});

  @override
  State<SmallCallWidget> createState() => _SmallCallWidgetState();
}

class _SmallCallWidgetState extends State<SmallCallWidget> {
  StreamSubscription? rtcStatusSubscription;
  List<RtcUserSession> remoteSessions = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setupSubscription();
    remoteSessions = ChatRTCManager.getInstance().remoteSessions;
  }

  @override
  void dispose() {
    rtcStatusSubscription?.cancel();
    super.dispose();
  }

  setupSubscription(){
    rtcStatusSubscription =
        EventBusUtils.getInstance().eventBus.on<RtcStatus>().listen((event) {
          // All events are of type UserLoggedInEvent (or subtypes of it).
          if (event.status == -1) {
            final mainLogic = Get.find<WhlMainLogic>();
            mainLogic.hideSmVideoView();
          }else {
            setState(() {
              remoteSessions = event.remoteSessions;
            });
          }
        });
  }

  @override
  Widget build(BuildContext context) {
    if (ChatRTCManager.getInstance().isVideoCall == true) {
      int myUid = ChatRTCManager.getInstance().myUid;
      RtcUserSession? session;
      if (remoteSessions.length == 1) {
        session = remoteSessions.first;
      }else if (remoteSessions.length > 1) {
        for (var element in remoteSessions) {
          if (element.uid != myUid) {
            session = element;
          }
        }
      }
      return UIContainer(
        child: session != null? NERtcVideoView.withInternalRenderer(
          uid: session.uid == myUid ? null : session.uid,
          subStream: session.subStream,
          mirrorListenable: session.mirror,
          rendererEventLister: ChatRTCManager.getInstance(),
          fitType: NERtcVideoViewFitType.cover,
        ):null,
        onTap: (){
          toBigVideoPage();
        },
      ) ;
    }
    return UIContainer(
      child: UIImage(
        width: 70.w,
        height: 70.w,
        assetPlaceHolder: WHLGlobalConfig.userPlaceholderAvatar,
        httpImage: ChatRTCManager.getInstance().userModel?.avatar?.toImageUrl(),
        radius: 35.w,
      ),
      onTap: (){
        toBigVideoPage();
      },
    );
  }


  toBigVideoPage(){
    final mainLogic = Get.find<WhlMainLogic>();
    mainLogic.hideSmVideoView();
    Get.toNamed(Routes.chatCallPage,arguments: {"isVideoCall":true,"uid":ChatRTCManager.getInstance().myUid});
  }
}